package com.myproject.thread.volatiles;

public class VolatileObjectTest implements Runnable {

    private volatile ObjectA objectA;

    public VolatileObjectTest(ObjectA objectA) {
        this.objectA = objectA;
    }

    public ObjectA getObjectA() {
        return objectA;
    }

    public void setObjectA(ObjectA objectA) {
        this.objectA = objectA;
    }

    @Override
    public void run() {
        long i = 0;
        while (!objectA.isFlag()) {
            i++;
        }
        System.out.println(Thread.currentThread().getName()+": stop My Thread " + i);
    }


    public static void main(String[] args) throws InterruptedException {

        ObjectA objectA = new ObjectA();
        VolatileObjectTest test = new VolatileObjectTest(objectA);
        Thread thread = new Thread(test);
        thread.start();

        Thread.sleep(5000);
        objectA.setFlag(true);
        System.out.println(Thread.currentThread().getName()+": flag is " + test.getObjectA().isFlag());
    }

    static class ObjectA {
        private boolean flag;

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

    }


}
